package it.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer_HelloWorld {

    public static void main(String[] args) throws IOException, TimeoutException {

        //1. 建立连接工厂
        ConnectionFactory factory = new ConnectionFactory();

        //2. 设置参数
        factory.setHost("192.168.1.113"); //ip  默认值localhost
        factory.setPort(5672);//端口  默认值5672
        factory.setUsername("guest");//用户名
        factory.setPassword("guest");//密码

        //3. 创建连接 Connection
        Connection connection = factory.newConnection();

        //4. 创建管道 Channel
        Channel channel = connection.createChannel();

        //5. 创建队列 Queue
        /**
         * queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
         *          1. queue:队列名称
         *          2. durable:是否持久化。mq重启后还在
         *          3. exclusive:
         *              是否独占，只有一个消费者监听这个队列
         *              connection关闭后是否删除队列
         *              一般情况设置为false
         *          4. autoDelete:是否自动删除。当没有consumer时自动删除
         *          5. arguments:参数
         * */
        channel.queueDeclare("hello_world",true,false,false,null);

        //6. 接收消息
        /**
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         *          1. queue:队列名称
         *          2. autoAck:是否自动确认
         *          3. callback:回调确认
         * */
        Consumer comsumer = new DefaultConsumer(channel){
            /*
                回调方法，当收到消息后，会自动执行该方法
                1. consumerTag:标识
                2. envelope:获取一些信息，交换机、路由器key....
                3. properties:配置信息
                4. body:数据
            * */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("consumer: " + consumerTag);
                System.out.println("envelopeExchange: " + envelope.getExchange());
                System.out.println("envelopeRoutingKey: " + envelope.getRoutingKey());
                System.out.println("properties: " + properties);
                System.out.println("body: " + new String(body));
            }
        };
        channel.basicConsume("hello_world",true,comsumer);

        //7. 释放资源
//        channel.close();
//        connection.close();

    }

}
